<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row class="changZindex">
            <a-col :md="12" :sm="24">
              <a-form-item label="法人行" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <a-select v-if="this.currentUser.admin" mode="default" :allowClear="true" style="width: 100%"
                  @change="handleInstChange" v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{ r.label }}-{{ r.value }}</a-select-option>
                </a-select>
                <a-input v-if="!this.currentUser.admin" v-model="queryParams.instId" :value="this.currentUser.instId"
                  :disabled="true" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId != ''" class="changMarginTop">
            <a-col :md="12" :sm="24">
              <a-form-item label="用户账号" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <a-input v-model="queryParams.loginId" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="所属机构" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <a-tree-select mode="default" :allowClear="true" style="width: 100%" :treeData="orgTreeData"
                  :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }" v-model="queryParams.orgId">
                  <!--                  :allowClear="true"-->
                  <!--                  :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"-->
                  <!--                  :treeData="orgTreeData"-->
                  <!--                  v-model="queryParams.orgId">-->
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="角色名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <a-input v-model="queryParams.roleName" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="用户姓名" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <a-input v-model="queryParams.userName" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="用户状态" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 2 }">
                <!--<a-input v-model="queryParams.userStatus"/>-->
                <a-select mode="default" v-model="queryParams.userStatus" :allowClear="true" style="width: 100%">
                  <a-select-option key="00">正常</a-select-option>
                  <a-select-option key="01">注销</a-select-option>
                  <a-select-option key="02">冻结</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!--          <template v-if="advanced">
                        <a-col :md="12" :sm="24" >
                          <a-form-item
                            label="创建时间"
                            :labelCol="{span: 4}"
                            :wrapperCol="{span: 18, offset: 2}">
                            <range-date @change="handleDateChange" ref="createTime"></range-date>
                          </a-form-item>
                        </a-col>
                      </template>-->
          </a-row>
        </div>
        <span v-show="queryParams.instId != ''" style="position: relative; left: -38%; top: -20px">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          <!--           <a @click="toggleAdvanced" style="margin-left: 8px">-->
          <!--            {{advanced ? '收起' : '展开'}}-->
          <!--            <a-icon :type="advanced ? 'up' : 'down'" />-->
          <!--          </a>-->
        </span>
      </a-form>
    </div>
    <div v-show="queryParams.instId != ''">
      <div class="operator">
        <a-button type="primary" ghost @click="add" v-hasPermission="['user:add']">新增</a-button>
        <a-button @click="batchDelete" v-hasPermission="['user:delete']">删除</a-button>
        <a-dropdown v-hasAnyPermission="['user:reset', 'user:export']">
          <a-menu slot="overlay">
            <a-menu-item v-hasPermission="['user:reset']" key="password-reset" @click="resetPassword">密码重置</a-menu-item>
            <a-menu-item v-hasPermission="['user:export']" key="export-data" @click="exportExcel">导出Excel</a-menu-item>
          </a-menu>
          <a-button>
            更多操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo" :columns="columns" :rowKey="record => record.id" :dataSource="dataSource"
        :pagination="pagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :scroll="{ x: 2200 }"
        @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{ text }}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{ text }}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="['user:update']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
            @click="edit(record)" title="修改用户"></a-icon>
          &nbsp;
          <a-icon v-hasPermission="['user:view']" type="eye" theme="twoTone" twoToneColor="#42b983"
            @click="view(record)" title="查看"></a-icon>
          <a-badge v-hasNoPermission="['user:update', 'user:view']" userStatus="warning" text="无权限"></a-badge>
        </template>
      </a-table>
    </div>
    <!-- 用户信息查看 -->
    <user-info :userInfoData="userInfo.data" :userInfoVisiable="userInfo.visiable" @close="handleUserInfoClose">
    </user-info>
    <!-- 新增用户 -->
    <user-add :userInst="this.queryParams.instId" :userOrgCode="this.currentUser.orgCode" @close="handleUserAddClose"
      @success="handleUserAddSuccess" :currentUser="this.currentUser" :userAddVisiable="userAdd.visiable">
    </user-add>
    <!-- 修改用户 -->
    <user-edit ref="userEdit" :userInst="this.queryParams.instId" :userOrgCode="this.currentUser.orgCode"
      @close="handleUserEditClose" @success="handleUserEditSuccess" :currentUser="this.currentUser"
      :userEditVisiable="userEdit.visiable">
    </user-edit>
  </a-card>
</template>

<script>
import UserInfo from './UserInfo'
// import DeptInputTree from '../dept/DeptInputTree'
import OrgInputTree from '../org/OrgInputTree'
import RangeDate from '@/components/datetime/RangeDate'
import UserAdd from './UserAdd'
import UserEdit from './UserEdit'
import { mapState } from "vuex"

export default {
  name: 'User',
  components: { UserInfo, UserAdd, UserEdit, OrgInputTree, RangeDate },
  data() {
    return {
      advanced: false,
      userInfo: {
        visiable: false,
        data: {}
      },
      userAdd: {
        visiable: false
      },
      userEdit: {
        visiable: false
      },
      queryParams: {
        instId: '',
        orgCode: '',
      },
      instIdData: [],
      parentOrgCode: '',
      userOrgCode: '',
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      orgTreeData: [],
      idToOrgCodeData: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.account.user
    }),
    columns() {
      let { sortedInfo, filteredInfo } = this
      sortedInfo = sortedInfo || {}
      filteredInfo = filteredInfo || {}
      return [{
        title: '用户类型',
        dataIndex: 'userType',
        width: 200,
        customRender: (text, row, index) => {
          switch (text) {
            case '00':
              return '统一支付平台内管'
            case '01':
              return '商户服务'
            case '02':
              return '第三方应用'
            default:
              return text
          }
        },
        filters: [
          { text: '统一支付平台内管', value: '00' },
          { text: '商户服务', value: '01' },
          { text: '第三方应用', value: '02' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.userType || null,
        onFilter: (value, record) => record.userType.includes(value)
      }, {
        title: '用户账号',
        dataIndex: 'loginId',
        width: 150,
      }, {
        title: '用户真实姓名',
        dataIndex: 'userName',
        width: 150,
      }, {
        title: '用户昵称',
        dataIndex: 'nickName',
        width: 150,
      }, {
        title: '性别',
        dataIndex: 'userSex',
        width: 150,
        customRender: (text, row, index) => {
          switch (text) {
            case '0':
              return '男'
            case '1':
              return '女'
            case '2':
              return '保密'
            default:
              return text
          }
        },
        filters: [
          { text: '男', value: '0' },
          { text: '女', value: '1' },
          { text: '保密', value: '2' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.userSex || null,
        onFilter: (value, record) => record.userSex.includes(value)
      }, {
        title: '所属机构',
        dataIndex: 'orgName',
        width: 150
      }, {
        title: '角色名称',
        dataIndex: 'roleName',
        editable: true,
        align: 'left',
        width: 150
      }, {
        title: '电话',
        dataIndex: 'mobileNo',
        width: 150
      }, {
        title: '邮箱',
        dataIndex: 'email',
        width: 150,
        scopedSlots: { customRender: 'email' }
      }, {
        title: '状态',
        dataIndex: 'userStatus',
        width: 150,
        customRender: (text, row, index) => {
          switch (text) {
            case '00':
              return <a-tag color="limegreen">正常</a-tag>
            case '01':
              return <a-tag color="silver">注销</a-tag>
            case '02':
              return <a-tag color="red">冻结</a-tag>
            default:
              return text
          }
        },
        filters: [
          { text: '正常', value: '00' },
          { text: '注销', value: '01' },
          { text: '冻结', value: '02' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.userStatus || null,
        onFilter: (value, record) => record.userStatus.includes(value)
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: (a, b) => { return a.createTime > b.createTime ? 1 : -1 }
      }, {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  mounted() {
    this.getInstList();
    // this.$get('admin/upmporg/getInstList').then((r) => {
    //   this.instIdData = r.data
    // })
    if (!this.currentUser.admin) {
      this.handleInstChange(this.currentUser.instId);
    }
    this.userOrgCode = this.currentUser.orgCode;
    console.log(this.currentUser);
    // this.fetch()
  },
  methods: {
    async getInstList() {
      const res = await this.$get('admin/upmporg/getInstList');
      this.instIdData = res.data
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
      if (!this.advanced) {
        this.queryParams.createTimeFrom = ''
        this.queryParams.createTimeTo = ''
      }
    },
    async handleInstChange(value) {
      this.queryParams.instId = value;
      if (value != "") {

        let params = {}
        params.instId = value;
        if (this.currentUser.admin) {
        } else {
          params.parentOrgCode = this.userOrgCode
        }
        const res = await this.$get('admin/upmporg', { ...params });
        this.orgTreeData = res.data.rows.children
        this.idToOrgCodeData = res.data.idToCode

        this.search();
      }
    },
    view(record) {
      this.userInfo.data = record
      this.userInfo.visiable = true
    },
    add() {
      this.userAdd.visiable = true
    },
    handleUserAddClose() {
      this.userAdd.visiable = false
    },
    handleUserAddSuccess() {
      this.userAdd.visiable = false
      this.$message.success('新增用户成功，并设置为默认密码')
      this.search()
    },
    edit(record) {
      if(record.userStatus=='01'){
      this.$message.warn('已注销的用户不可修改')
      return
      }
      this.$refs.userEdit.setFormValues(record)
      this.userEdit.visiable = true
    },
    handleUserEditClose() {
      this.userEdit.visiable = false
    },
    handleUserEditSuccess() {
      this.userEdit.visiable = false
      this.$message.success('修改用户成功')
      this.search()
    },
    handleUserInfoClose() {
      this.userInfo.visiable = false
    },
    handleOrgChange(value) {
      this.queryParams.orgCode = value || ''
    },
    handleDateChange(value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    batchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk() {
          let userIds = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          userIds.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.id + ',') > -1 }).map(m => { return m.id }))
          that.$delete('admin/upmpuser/' + userIds.join(',')).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message)
              that.selectedRowKeys = []
              that.search()
            } else {
              this.$message.error(res.data.message)
            }
          }).catch((r) => {
            console.error(r)
            that.$message.error('删除用户失败')
          })
        },
        onCancel() {
          that.selectedRowKeys = []
        }
      })
    },
    resetPassword() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要重置密码的用户')
        return
      }
      let that = this
      this.$confirm({
        title: '确定重置选中用户密码?',
        content: '当您点击确定按钮后，这些用户的密码将会重置',
        centered: true,
        onOk() {
          let ids = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          ids.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.id + ',') > -1 }).map(m => { return m.id }))
          that.$put('admin/upmpuser/password/reset', {
            ids: ids.join(',')
          }).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message)
              that.selectedRowKeys = []
            } else {
              this.$message.error(res.data.message)
            }
          }).catch((r) => {
            console.error(r)
            that.$message.error('重置用户密码失败')
          })
        },
        onCancel() {
          that.selectedRowKeys = []
        }
      })
    },
    exportExcel() {
      let { sortedInfo, filteredInfo } = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.$export('admin/upmpuser/excel', {
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    search() {
      let { sortedInfo, filteredInfo } = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      if ("" != this.queryParams.orgId) {
        this.queryParams.orgCode = this.idToOrgCodeData[this.queryParams.orgId];
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset() {
      this.queryParams.instId=''
      this.queryParams.loginId=''
      this.queryParams.roleName=''
      this.queryParams.orgId=undefined
      this.queryParams.userName=''
      this.queryParams.userStatus=''
      // 取消选中
      this.selectedRowKeys = []
      // // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // // 重置列过滤器规则
      // this.filteredInfo = null
      // // 重置列排序规则
      // this.sortedInfo = null
      // // 重置查询参数
      // this.queryParams = {}
      // // 清空部门树选择
      // // this.$refs.orgTree.reset()
      // // 清空时间选择
      // // if (this.advanced) {
      // //   this.$refs.createTime.reset()
      // // }
      
      if (!this.currentUser.admin) {
        this.handleInstChange(this.currentUser.instId);
      }
    },
    handleTableChange(pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.userInfo.visiable = false
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    async fetch(params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      await this.$get('admin/upmpuser', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";

.operator {
  //margin-top: 70px;
}

.changZindex {
  width: 100%;
  z-index: 10;
}

.changMarginTop {
  position: relative;
  top: 8px;
}
</style>
